package com.code.exam.controller;


import com.code.exam.annotation.LoginCheck;
import com.code.exam.common.result.PageResult;
import com.code.exam.common.result.Result;
import com.code.exam.dto.TiIdsDTO;
import com.code.exam.dto.ExamCreateDTO;
import com.code.exam.dto.ExamPageQueryDTO;
import com.code.exam.entity.Exam;
import com.code.exam.service.ExamService;
import com.code.exam.vo.*;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping("/admin/exam")
public class ExamController {

    @Autowired
    private ExamService examService;


    @PostMapping("/create")
    @LoginCheck(role = "admin")
    @ApiOperation("创建考试")
    public Result<ExamVO> examcreate(@RequestBody ExamCreateDTO examCreateDTO) {

        log.info("管理员创建考试{}", examCreateDTO);
        if (examCreateDTO.getStartTime().isAfter(examCreateDTO.getEndTime())) {
            log.info("结束时间不能早于开始时间");
            return Result.error("结束时间不能早于开始时间");
        } else {
            Exam exam = examService.examcreate(examCreateDTO);
            ExamVO examVO = ExamVO.builder()
                    .examId(exam.getId())
                    .title(exam.getTitle())
                    .startTime(exam.getStartTime())
                    .endTime(exam.getEndTime())
                    .status(exam.getStatus())
                    .build();
            return Result.success("考试创建成功", examVO);
        }
    }


    @PatchMapping("/{examId}")
    @LoginCheck(role = "admin")
    @ApiOperation("更新考试状态")
    public Result updateStatus(@PathVariable Long examId, @RequestBody Map<String, String> updates) {
        String status = updates.get("status");
        log.info("当前考试状态为{}", status);
        try {
            Exam exam = examService.updateStatus(examId, status);
            ExamVO examVO = ExamVO.builder()
                    .examId(exam.getId())
                    .status(exam.getStatus())
                    .build();
            return Result.success("考试状态更新成功", examVO);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }

    }


    @GetMapping("/list")
    @LoginCheck(role = "admin")
    @ApiOperation("查询考试列表")
    public Result<PageResult<EPageResultVO>> pageQuery(ExamPageQueryDTO examPageQueryDTO) {
        log.info("查询考试列表{}", examPageQueryDTO);
        PageResult<EPageResultVO> pageResult = examService.pageQuery(examPageQueryDTO);
        return Result.success("查询成功", pageResult);
    }

    @PostMapping("/{examId}/add-questions")
    @LoginCheck(role = "admin")
    @ApiOperation("为考试添加题目(组卷)")
    public Result addQuestions(@PathVariable Long examId, @RequestBody TiIdsDTO addTiIdsDTO) {

        log.info("考试唯一ID：{}", examId);
        log.info( "添加题目ID数组：{}", addTiIdsDTO);

        String status = examService.getStatus(examId);
        if (status == null) {
            return Result.error("考试Id不存在");
        } else if (status.equals("IN_PROGRESS")) {
            return Result.error("考试已开始，无法添加题目");
        } else {
            AddTiIdsVO addTiIdsVO = examService.addQuestions(examId, addTiIdsDTO);
            return Result.success("成功添加%d道题到考试中", addTiIdsVO.getAddedCount(), addTiIdsVO);
        }
    }

    @DeleteMapping("/{examId}/remove-questions")
    @LoginCheck(role = "admin")
    @ApiOperation("从考试移除题目")
    public Result removeTi(@PathVariable Long examId, @RequestBody TiIdsDTO tiIdsDTO){
        log.info("考试唯一Id：{}",examId);
        log.info("要移除题目的ID数组：{}",tiIdsDTO);
        String status = examService.getStatus(examId);
        if (status == null) {
            return Result.error("考试Id不存在");
        } else if (status.equals("IN_PROGRESS")) {
            return Result.error("考试已开始，无法删除题目");
        } else {
            int removedCount = examService.removeTi(examId,tiIdsDTO);
            RemoveTiVO removeTiVO = new RemoveTiVO();
            removeTiVO.setRemovedCount(removedCount);
            return Result.success("成功从考试中移除%d道题",removedCount,removeTiVO);
        }
    }

    @GetMapping("/{examId}/questions")
    @LoginCheck(role = "admin")
    @ApiOperation("获取考试下所有题目")
    public Result getQuestions(@PathVariable Long examId){
        log.info("考试唯一Id：{}",examId);
        ExamAllquestionsVO examAllquestionsVO = new ExamAllquestionsVO<>();
        examAllquestionsVO = examService.getAllQuestions(examId);
        return Result.success("获取考试题目成功",examAllquestionsVO);

    }
}
